<?php

require("./config.php");

if (!isset($_POST['req'])) {
    die("No request provided.");
} else {
    if (filter_input(INPUT_POST, 'req') == "login") {
        
        $json = array("success" => false, "msg" => "", "tipo" => "fail", "user" => "");
        
        if (!isset($_SESSION['logged']) || $_SESSION['logged'] == "no") {

            $user = $dbConn->real_escape_string(filter_input(INPUT_POST, 'user'));
            $pw = $dbConn->real_escape_string(filter_input(INPUT_POST, 'pass'));

            $query = "SELECT CLAVE_USUARIO, TIPO_USUARIO FROM USUARIO WHERE PK_USUARIO_ID_USUARIO = '" . $user . "';";
            $result = $dbConn->query($query);

            $info = $result->fetch_row();

            if (crypt($pw, $info[0]) == $info[0]) {
                $json['tipo'] = $info[1];
                $json['success'] = true;
                $json['msg'] = "You're Logged in!";
                $json['user'] = $user;
                $_SESSION['logged'] = "yes";
                $_SESSION['user'] = $user;
                $_SESSION['succes'] = true;
                $_SESSION['tipo'] = $info[1];
            } else {
                $json['msg'] = "Usuario y/o Contraseña son incorrectas";
            }
        } else {
            $json['user'] = $_SESSION['user'];
            $json['success'] = $_SESSION['succes'];
            $json['tipo'] = $_SESSION['tipo'];
            $json['msg'] = "You're already logged!";
        }

        print(json_encode($json));
    }
}
